
package com.amigo.online.provider.merchant.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.amigo.online.common.base.service.BaseService;
import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.common.param.RedisKey;
import com.amigo.online.common.param.dto.merchant.CommentReplyDto;
import com.amigo.online.common.param.result.merchant.MerchantCommentInfo;
import com.amigo.online.common.param.result.merchant.MerchantManagerInfo;
import com.amigo.online.provider.merchant.common.GlobalController;
import com.amigo.online.provider.merchant.common.MerchantRedisKey;
import com.amigo.online.provider.merchant.common.RwRedisService;
import com.amigo.online.provider.merchant.exception.MerchantException;
import com.amigo.online.provider.merchant.mapper.GoodsCommentMapper;
import com.amigo.online.provider.merchant.mapper.MerchantManagerMapper;
import com.amigo.online.provider.merchant.mapper.MerchantMapper;
import com.amigo.online.provider.merchant.model.entity.GoodsComment;
import com.amigo.online.provider.merchant.model.entity.MerchantManager;
import com.amigo.online.provider.merchant.service.MerchantManagerService;
import com.amigo.online.provider.merchant.utils.ConvertUtil;

/**
 * <code>MerchantManagerServiceImpl.java</code>
 * <p>
 *
 * </p>
 * <p>
 *
 * @author LuChen
 * @version 1.0
 * @company Amigo
 * @time 2018年12月21日 下午3:51:37
 * @lastUpdate 无
 * </p>
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MerchantManagerServiceImpl extends BaseService<MerchantManager> implements MerchantManagerService {

    @Autowired
    private RwRedisService redisService;

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private GoodsCommentMapper goodsCommentMapper;

    @Autowired
    private MerchantManagerMapper merchantManagerMapper;


    @Override
    @SuppressWarnings("unchecked")
    public boolean addManager(Long merchantId, Long userId) {
        Long id = GlobalController.getNowUser().getId();
        if (merchantMapper.checkManager(merchantId, id) == 0) {
            throw new MerchantException(StatusCode.FORBIDDEN);
        }
        //检验是不是其他店的店长
        if (merchantMapper.checkMerchantKeeper(userId) > 0) {
            throw new MerchantException(StatusCode.CAN_NOT_ADD_OTHER_STOREKEEPER);
        }
        MerchantManager merchantManager = new MerchantManager();
        merchantManager.setMerchantId(merchantId);
        merchantManager.setUserId(userId);
        merchantManager.setQuit(0);
        if (merchantManagerMapper.select(merchantManager).size() > 0) {
            throw new MerchantException(StatusCode.ALREADY_IS_MANAGER);
        }
        merchantManager.setCreatedTime(System.currentTimeMillis() / 1000);
        //判断之前是否加入又退出
        if (merchantManagerMapper.checkManagerBefore(merchantId, userId) == 0) {
            merchantManagerMapper.insert(merchantManager);
        } else {
            merchantManagerMapper.updateQuit(merchantManager);
        }
        String merchant_status_key = RedisKey.MERCHANT_STATUS_KEY + userId;
        redisService.opsForValue().set(merchant_status_key, 4);
        Long redisResult = redisService.opsForSet().add(MerchantRedisKey.MERCHANT_MANAGER_SET, userId);
        if (redisResult == 0) {
            logger.error("添加商家的管理员缓存数据有误，商家ID:{},管理员ID:{}", merchantId, userId);
        }
        return true;
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean removeManager(Long merchantId, Long userId) {
        Long id = GlobalController.getNowUser().getId();
        if (merchantMapper.checkManager(merchantId, id) == 0) {
            throw new MerchantException(StatusCode.FORBIDDEN);
        }
        MerchantManager merchantManager = new MerchantManager();
        merchantManager.setMerchantId(merchantId);
        merchantManager.setUserId(userId);
        merchantManager.setQuit(1);
        merchantManager.setQuitTime(System.currentTimeMillis() / 1000);
        int result = merchantManagerMapper.updateQuit(merchantManager);
        if (result == 0) {
            logger.error("移除管理员更新失败。");
        }
        String merchant_status_key = RedisKey.MERCHANT_STATUS_KEY + userId;
        redisService.opsForValue().getOperations().delete(merchant_status_key);
        Long redisResult = redisService.opsForSet().remove(MerchantRedisKey.MERCHANT_MANAGER_SET, userId);
        if (redisResult == 0) {
            logger.error("移除商家的管理员缓存数据有误，商家ID:{},管理员ID:{}", merchantId, userId);
        }
        return true;
    }

    @Override
    public List<MerchantManagerInfo> getManagerList(Long merchantId) {
        Long id = GlobalController.getNowUser().getId();
        List<MerchantManager> list = merchantManagerMapper.getManagerListByMerchantId(merchantId);
        List<MerchantManagerInfo> info = ConvertUtil.merchantManagerToManagerInfo(list);
        return info;
    }


    @Override
    public JSONObject reply(CommentReplyDto dto) {
        GoodsComment goodsComment = new GoodsComment();
        goodsComment.setId(dto.getCommentId());
        goodsComment.setBackContent(dto.getContent());
        goodsComment.setBackTime(System.currentTimeMillis() / 1000);
        goodsCommentMapper.replyComment(goodsComment);
        JSONObject result = new JSONObject();
        result.put("commentId", dto.getCommentId());
        result.put("content", dto.getContent());
        result.put("time", System.currentTimeMillis() / 1000);
        return result;
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean quitManager(Long merchantId) {
        Long id = GlobalController.getNowUser().getId();
        MerchantManager merchantManager = new MerchantManager();
        merchantManager.setMerchantId(merchantId);
        merchantManager.setUserId(id);
        merchantManager.setQuit(1);
        merchantManager.setQuitTime(System.currentTimeMillis() / 1000);
        int result = merchantManagerMapper.updateQuit(merchantManager);
        if (result == 0) {
            logger.error("移除管理员更新失败。");
        }
        String merchant_status_key = RedisKey.MERCHANT_STATUS_KEY + id;
        redisService.opsForValue().getOperations().delete(merchant_status_key);
        Long redisResult = redisService.opsForSet().remove(MerchantRedisKey.MERCHANT_MANAGER_SET, id);
        if (redisResult == 0) {
            logger.error("移除商家的管理员缓存数据有误，商家ID:{},管理员ID:{}", merchantId, id);
        }
        return true;
    }

}

